package fc;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import fc.entity.OaEntity;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.upgradetool.wscheck.Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ZH_LSCG_XQ implements Action{

	@Override
	public String execute(RequestInfo info) {
		String API_NAME="ZH_LSCG_XQ";

		BaseBean log = new BaseBean();

		log.writeLog("接口"+API_NAME+"开始调用-----------------------------------");

		OaEntity oe=new OaEntity();

		String requestid = info.getRequestid();
		String tablename = info.getRequestManager().getBillTableName();
		oe.setREQUESTID(requestid);

		String sql=
				"SELECT requestid,BH,' ' SYDH,项目编号 XMBH,实验名称 SYMC,ccbm 产出部门,sqry ,rem from ( " +
						"select requestid,BH,xmbh 项目编号,khmc 实验名称,ccbm ,sqry ,isnull(jxmc,'')+'+'+isnull(khmc,'')+'+'+isnull(bh,'')+'+'+isnull(sbph,'')  rem  from "+tablename+"  o1  with(nolock)  " +
						"where requestid="+requestid+")t ";
		RecordSet rs = new RecordSet();
		rs.executeSql(sql);
		if(rs.next()){
			oe.setREQUESTID(Util.null2String(rs.getString("requestid")));

			oe.setGCAH(Util.null2String(rs.getString("BH")));
			oe.setSYMC(Util.null2String(rs.getString("SYMC")));

			oe.setXMBH(Util.null2String(rs.getString("XMBH")));
			oe.setREQUESTID(Util.null2String(rs.getString("REQUESTID")));
			oe.setCCBM(Util.null2String(rs.getString("产出部门")));
			oe.setUSERID(Util.null2String(rs.getString("sqry")));
			oe.setREM(Util.null2String(rs.getString("rem")));

			if("".equals(oe.getCCBM())){oe.setCCBM("");}
		}

		String sql1="select 料件编号 LJBH,数量 SL,单位 DW,物料需求时间 WLXQSJ,REM  from (" +
				"select  o1.id,o1.ljbh  料件编号,o1.SL 数量,o1.dw 单位," +
				"case when o1.wlxqrq <cast(getdate() as date ) then cast(getdate() as date ) else o1.wlxqrq end  物料需求时间 ,o1.YT   REM  "+
				"from "+tablename+"_dt1 o1 with(nolock) ,"+tablename+" o2 with(nolock)   " +
				"where o1.mainid=o2.id and  o2.requestid="+requestid+")tt   order by id  ";

		RecordSet rs1 = new RecordSet();
		rs1.executeSql(sql1);
		while(rs1.next()){
			List<OaEntity> dts=oe.getDT1();
			OaEntity dt1=new OaEntity();

			dt1.setLJBH(Util.null2String(rs1.getString("LJBH")));
			dt1.setSL(Util.null2String(rs1.getString("SL")));
			dt1.setDW(Util.null2String(rs1.getString("DW")));
			dt1.setWLXQSJ(Util.null2String(rs1.getString("WLXQSJ")));
			dt1.setREM(Util.null2String(rs1.getString("REM")));


			dts.add(dt1);
			oe.setDT1(dts);
		}


		String testparam="";
		log.writeLog("接口"+API_NAME+"参数开始-----------------------------------"+oe.getREQUESTID());

		log.writeLog("main-----------------------------------");
		log.writeLog("工程案号 GCAH:"+oe.getGCAH()+",实验单号 SYDH:"+oe.getSYDH());
		testparam="";
		log.writeLog("dt1-----------------------------------");


		for(int i=0;i<oe.getDT1().size();i++){
			log.writeLog("料件编号 LJBH:"+oe.getDT1().get(i).getLJBH()+
					",数量 SL:"+oe.getDT1().get(i).getSL()+
					",单位 DW:"+oe.getDT1().get(i).getDW()+
					",物料需求时间 WLXQSJ:"+oe.getDT1().get(i).getWLXQSJ()
			);
			oe.setWLXQSJ(oe.getDT1().get(i).getWLXQSJ());
			if (!"".equals(testparam)){
				testparam=testparam+",";
			}
			testparam+=
					"{"+
							"\"idx\": \""+(i+1)+"\","+
							"\"code\": \""+oe.getDT1().get(i).getLJBH()+"\","+
							"\"requst_date\": \""+oe.getDT1().get(i).getWLXQSJ()+"\","+
							"\"amount\": "+oe.getDT1().get(i).getSL()+","+
							"\"project\": \""+oe.getXMBH()+"\","+
							"\"memo\": \""+oe.getDT1().get(i).getREM()+"\""+
							"}";


		}


		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String  timestamp= format.format(new Date());


		DateFormat formataa = new SimpleDateFormat("yyyy-MM-dd");

		String createdate = formataa.format(new Date());

		String creater=oe.getUSERID();



		String json_param=
"{"+
		"\"key\": \"f5458f5c0f9022db743a7c0710145903\","+
		"\"type\": \"sync\","+
		"\"host\": {"+
		"\"prod\": \"oa\","+
		"\"ip\": \"192.168.0.1\","+
		"\"lang\": \"zh_CN\","+
		"\"acct\": \"tiptop\","+
		"\"timestamp\": \""+timestamp+"\""+
		"},"+
		"\"service\": {"+
		"\"prod\": \"T100\","+
		"\"name\": \"apst300_crt\","+
		"\"ip\": \"192.168.0.2\","+
		"\"id\": \"topprd\""+
		"},"+
		"\"datakey\": {"+
		"\"EntId\": \"2\","+
		"\"CompanyId\": \"ZH00\""+
		"},"+
		"\"payload\": {"+
		"\"std_data\": {"+
		"\"parameter\": {"+
		"\"p1\": \"\","+
		"\"p2\": \"\""+
		"}"+
		"},"+
		"\"param\": {"+
		"\"top\": {"+
		"\"user_code\": \""+creater+"\","+
		"\"source_doc\": \""+oe.getREQUESTID()+"\","+
		"\"memo\": \""+oe.getREM()+"\""+
		"},"+
		"\"data\": ["+
		testparam+
		"]"+
		"}"+
		"}"+
		"}";


		log.writeLog("接口"+API_NAME+"json_param:"+json_param);

		String result="ERROR";

		if(!"".equals(testparam)){
			String data = HttpRequest.post(FcHttpCon.ZH_YFSY_XQ).body(json_param).execute().body();
			log.writeLog("接口"+API_NAME+"返回-----------------------------------"+data);
			try {

				Object succesResponse = JSON.parse(data);
				Map map = (Map) succesResponse;
				Map map1 = (Map) map.get("payload");
				Map map2 = (Map) map1.get("std_data");
				Map map3 = (Map) map2.get("execution");

				if("0".equals(map3.get("code"))){
					result="SUCCESS";
				}else{
					result=map3.get("description").toString();
				}

			} catch (Exception e) {}
		}else{
			result="NOTNEED";
		}



		if("SUCCESS".equals(result)){
			//记录数据
			RecordSet rsg = new RecordSet();
			String sqlg="INSERT INTO FC_API_DIAOYONG_JILU VALUES('"+API_NAME+"',"+requestid+",GETDATE())";
			rsg.executeSql(sqlg);
		}else if("NOTNEED".equals(result)){
		}else{
			if("ERROR".equals(result)) {
				info.getRequestManager().setMessagecontent("接口调用失败无法提交！请联系管理员具体查看");
			}else{
				info.getRequestManager().setMessagecontent(result);
			}
			return FAILURE_AND_CONTINUE;
		}
		return SUCCESS;


	}

	public static String sendPost(String url, String param) {

		PrintWriter out = null;
		BufferedReader in = null;
		StringBuilder result = new StringBuilder();
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			conn.setRequestProperty("contentType", "UTF-8");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
//			System.out.println("发送 POST 请求出现异常！" + e);
			result = new StringBuilder("{\"msg\":\"SB\",\"errCode\":\"1001\"}");
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result.toString();
	}





} 